import asyncio

from rest_framework.views import APIView

from HomeAutoAI.common.utils.ThreadLocal import get_cur_user
from llm.models import Threads
from llm.service.ThreadService import ThreadService
from users.models import Users

from HomeAutoAI.common.Results import HttpResult


class GetThreads(APIView):
    def get(self, request):
        user: Users = get_cur_user()
        print("GetThreads: user:", user)
        try:
            threads: list[Threads] = ThreadService.get_all(user=user)
            thread_ids: list[str] = []
            for thread in threads:
                thread_ids.append(thread.thread_id)
        except Exception as e:
            return HttpResult.error(message=str(e))
        return HttpResult.success(message="获取所有线程成功", data=thread_ids)


class GetHistoryMessages(APIView):
    def post(self, request):
        thread_id = request.data['thread_id']
        try:
            print("GetHistoryMessages: thread_id:", thread_id)
            messages = ThreadService.get_history_messages(thread_id=thread_id)
            return HttpResult.success(message="获取历史消息成功", data=messages)
        except Exception as e:
            return HttpResult.error(message=str(e))
